package com.test.langchain4j.config;

import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolProvider;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 2025/8/8 15:13
 * @modifiedBy:
 * @version: 1.0
 */
public class AiServiceFactory {
  /**
   * Gets ai service.
   *
   * @param <T> the type parameter
   * @param serviceClass the service class
   * @param streamingChatModel the streaming chat model
   * @param commands the commands
   * @return the ai service
   */
  public static <T> T getAiService(
      Class<T> serviceClass,
      StreamingChatModel streamingChatModel,
      List<String> commands,
      Map<String, String> env) {
    // 1.构建McpTransport协议
    McpTransport transport =
        new StdioMcpTransport.Builder().command(commands).environment(env).build();
    // 2.构建McpClient客户端
    McpClient mcpClient = new DefaultMcpClient.Builder().transport(transport).build();
    // 3.创建工具集和原生的FunctionCalling类似
    ToolProvider toolProvider = McpToolProvider.builder().mcpClients(mcpClient).build();
    // 4.通过AiServivces给我们自定义接口McpService构建实现类并将工具集和大模型赋值给AiService
    return AiServices.builder(serviceClass)
        .streamingChatModel(streamingChatModel)
        .toolProvider(toolProvider)
        .build();
  }
}
